package GUIHelper;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.BoxLayout;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import ControlLayer.RBDateCtr;
import ControlLayer.RoomCtr;

import GUILayer.RoomTypeModelGUI;

import ModelLayer.RBDate;

public class RoomTypeTablePanel extends JPanel {
	private static final long serialVersionUID = 1L;
	private RoomTypeModelGUI rtMGUI;
	private JButton btnBackward;
	private JButton btnForward;

	private JLabel lblTime;
	private JLabel lblRed;
	private JLabel lblGreen;
	private JLabel lblYellow;
	private JLabel lblredInfo;
	private JLabel lblgreenInfo;
	private JLabel lblyellowInfo;

	private JPanel tablePanel;
	private JScrollPane scrollPane;
	private DefaultTableModel tablemodel;
	private JTable table;

	private ColorRenderer colorRenderer;
	private RBDateCtr rbDateCtr;
	private RoomCtr roomCtr;
	private Date date;
	private JPanel thisPanel;

	public RoomTypeTablePanel(JPanel panel) {
		date = Calendar.getInstance().getTime();
		rbDateCtr = new RBDateCtr();
		roomCtr = new RoomCtr();
		rtMGUI = (RoomTypeModelGUI) panel;
		colorRenderer = new ColorRenderer();
		thisPanel = this;
		initialize();
	}

	public void initialize() {
		this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		btnBackward = new JButton("<");
		btnForward = new JButton(">");
		lblTime = new JLabel();

		JPanel btnPanel = new JPanel();
		btnPanel.setLayout(new FlowLayout());
		btnPanel.add(btnBackward);
		btnPanel.add(btnForward);
		btnPanel.add(lblTime);

		btnBackward.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					thisPanel.setCursor(Cursor
							.getPredefinedCursor(Cursor.WAIT_CURSOR));
					Calendar s = Calendar.getInstance();
					s.setTime(date);
					s.add(Calendar.MONTH, -1);
					date = s.getTime();
					addTable(date);
				} finally {
					thisPanel.setCursor(Cursor.getDefaultCursor());
				}
			}
		});

		btnForward.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					thisPanel.setCursor(Cursor
							.getPredefinedCursor(Cursor.WAIT_CURSOR));

					Calendar s = Calendar.getInstance();
					s.setTime(date);
					s.add(Calendar.MONTH, 1);
					date = s.getTime();
					addTable(date);
				} finally {
					thisPanel.setCursor(Cursor.getDefaultCursor());
				}

			}
		});

		// TODO add table

		tablePanel = new JPanel();
		tablemodel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tablemodel.addColumn("Sun");
		tablemodel.addColumn("Mon");
		tablemodel.addColumn("Tue");
		tablemodel.addColumn("Wed");
		tablemodel.addColumn("Thr");
		tablemodel.addColumn("Fri");
		tablemodel.addColumn("Sat");

		scrollPane = new JScrollPane();
		tablePanel.add(scrollPane);
		table = new JTable(tablemodel);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		table.setAutoCreateRowSorter(true);
		table.setDefaultRenderer(Object.class, colorRenderer);

		scrollPane.setViewportView(table);
		table.setPreferredScrollableViewportSize(new Dimension(400, 192));

		Date today = Calendar.getInstance().getTime();
		addTable(today);

		lblRed = new JLabel("      ");
		lblGreen = new JLabel("      ");
		lblYellow = new JLabel("      ");
		lblRed.setOpaque(true);
		lblGreen.setOpaque(true);
		lblYellow.setOpaque(true);
		lblredInfo = new JLabel();
		lblgreenInfo = new JLabel();
		lblyellowInfo = new JLabel();
		lblRed.setBackground(Color.red);
		lblGreen.setBackground(Color.GREEN);
		lblYellow.setBackground(Color.YELLOW);
		lblredInfo.setText("No room left for booking");
		lblyellowInfo.setText("One room left for booking");
		lblgreenInfo.setText("More than two rooms left for booking");

		JPanel infoPanel = new JPanel();

		this.add(btnPanel);
		this.add(tablePanel);
		this.add(infoPanel);

		infoPanel.setLayout(new FlowLayout());
		infoPanel.add(lblRed);
		infoPanel.add(lblredInfo);
		infoPanel.add(lblYellow);
		infoPanel.add(lblyellowInfo);
		infoPanel.add(lblGreen);
		infoPanel.add(lblgreenInfo);

		// GroupLayout gl = new GroupLayout(infoPanel);
		// infoPanel.setLayout(gl);
		// gl.setAutoCreateGaps(true);
		// gl.setAutoCreateContainerGaps(true);
		//
		// gl.setHorizontalGroup(gl
		// .createSequentialGroup()
		// .addGroup(
		// gl.createParallelGroup(GroupLayout.Alignment.LEADING)
		// .addComponent(lblRed)
		// .addComponent(lblYellow)
		// .addComponent(lblGreen))
		// .addGroup(
		// gl.createParallelGroup(GroupLayout.Alignment.LEADING)
		// .addComponent(lblredInfo)
		// .addComponent(lblyellowInfo)
		// .addComponent(lblgreenInfo)));
		// gl.setVerticalGroup(gl
		// .createSequentialGroup()
		// .addGroup(
		// gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		// .addComponent(lblRed)
		// .addComponent(lblredInfo))
		// .addGroup(
		// gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		// .addComponent(lblYellow)
		// .addComponent(lblyellowInfo))
		// .addGroup(
		// gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
		// .addComponent(lblGreen)
		// .addComponent(lblgreenInfo)));
		//
	}

	public void addTable(Date date) {
		tablemodel.setRowCount(0);
		// if (tablemodel.getRowCount()!=0) {
		// for (int i = 0; i<12; i++) {
		// tablemodel.removeRow(0);
		// }
		// }

		// add 12 rows
		for (int i = 0; i < 12; i++) {
			tablemodel.addRow(new Object[] { "", "", "", "", "", "", "" });
		}

		// the first day for current month to insert the table
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.DAY_OF_MONTH, 1);

		lblTime.setText(new SimpleDateFormat("MM/yyyy").format(date));
		c.setFirstDayOfWeek(Calendar.SUNDAY);
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		int daysOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
		;
		int count = 1;
		boolean isFirstDayAdded = false;

		// insert date to calendar
		for (int i = 0; i < 12; i = i + 2) {
			for (int j = 0; j < 7; j++) {
				if (!isFirstDayAdded) {
					if (dayOfWeek == 1) { // if the first day start with Sun
						tablemodel.setValueAt(count, i, j);
						isFirstDayAdded = true;
						count++;
					} else if (j == (dayOfWeek - 1)) { // if the first day start
														// with Mon, Tue, Wed,
														// Thr, Fri, Sat
						tablemodel.setValueAt(count, i, j);
						isFirstDayAdded = true;
						count++;
					}
				} else {
					if (count <= daysOfMonth)
						tablemodel.setValueAt(count, i, j);
					count++;
				}

			}

		}
		// insert the number of available rooms for each date in the month
		boolean isFirstValueAdded = false;
		Calendar s = Calendar.getInstance();
		s.setTime(date);
		s.set(Calendar.DAY_OF_MONTH, 1);
		Date monthStartDate = s.getTime();
		LinkedList<RBDate> dates = rbDateCtr.getAllRBDateForMonth(rtMGUI
				.getRt().getId(), monthStartDate);
		// TODO check if it contains null value
		int nrOfAvailableroom = 0;
		int maxAvailableRoom = 0;
		maxAvailableRoom = roomCtr.getAvailableRoomsNrForRT(rtMGUI.getRt()
				.getId());
		// if (!dates.contains(null)) {
		int count2 = 0;
		for (int i = 1; i < 13; i = i + 2) {
			for (int j = 0; j < 7; j++) {

				if (!isFirstValueAdded) {
					if (dayOfWeek == 1) {
						if (dates.get(count2) != null)
							nrOfAvailableroom = dates.get(count2)
									.getNrOfAvailableRoom();
						else
							nrOfAvailableroom = maxAvailableRoom;
						tablemodel.setValueAt(nrOfAvailableroom, i, j);
						isFirstValueAdded = true;
						count2++;
					} else if (j == (dayOfWeek - 1)) {
						if (dates.get(count2) != null)
							nrOfAvailableroom = dates.get(count2)
									.getNrOfAvailableRoom();
						else
							nrOfAvailableroom = maxAvailableRoom;
						tablemodel.setValueAt(nrOfAvailableroom, i, j);
						isFirstValueAdded = true;
						count2++;
					}
				} else {
					if (count2 < daysOfMonth) {
						if (dates.get(count2) != null)
							nrOfAvailableroom = dates.get(count2)
									.getNrOfAvailableRoom();
						else
							nrOfAvailableroom = maxAvailableRoom;
						tablemodel.setValueAt(nrOfAvailableroom, i, j);
					}
					count2++;
				}

			}

		}
		// }
	}

	public JLabel getLblTime() {
		return lblTime;
	}

	public void setLblTime(JLabel lblTime) {
		this.lblTime = lblTime;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public class ColorRenderer extends DefaultTableCellRenderer {
		private static final long serialVersionUID = 1L;

		public ColorRenderer() {
			setOpaque(true); // MUST do this for background to show up.
		}

		public Component getTableCellRendererComponent(JTable table,
				Object color, boolean isSelected, boolean hasFocus, int row,
				int column) {
			JLabel cell = (JLabel) super.getTableCellRendererComponent(table,
					color, isSelected, hasFocus, row, column);
			if (row % 2 == 0) {
				cell.setBackground(Color.GRAY);
			} else {
				if (cell.getText().equals(""))
					cell.setBackground(Color.GRAY);
				else if (cell.getText().equals("0"))
					cell.setBackground(Color.RED);
				else if (cell.getText().equals("1"))
					cell.setBackground(Color.YELLOW);
				else
					cell.setBackground(Color.GREEN);

			}
			return this;
		}

	}
}
